/**
 * @desc 前端首页
 */

const express = require('express')
const router = express.Router()
const User = require('../models/user')
const Category = require('../models/category')
const Content = require('../models/content')

// 获取首页信息
router.get('/', (req, res) => {
  let data = {
    userInfo: req.userInfo,
    categories: [],
    category: req.query.category || '',
    count: 0,
    page: Number(req.query.page || 1),
    limit: 10,
    pages: 0,
    contents: []
  }

  // 获取分类条件
  let WHERE = {}
  if (data.category) {
    WHERE.category = data.category
  }

  // 获取首页基本信息
  Category.find().sort({
    _id: -1
  }).then(categories => { // 获取分类信息
    data.categories = categories
    return Content.countDocuments().where(WHERE)
  }).then(count => { // 获取内容数量
    data.count = count
    data.pages = Math.ceil(data.count / data.limit)
    data.page = Math.min(data.page, data.pages)
    data.page = Math.max(data.page, 1)
    skip = (data.page - 1) * data.limit
    return Content.find().where(WHERE).sort({
      addTime: -1
    }).limit(data.limit).skip(data.skip).populate(['category', 'user'])
  }).then(contents => { // 获取内容
    data.contents = contents
  }).then(() => {
    res.render('main/index', data)
  })
})

// 获取详细信息
router.get('/view', (req, res) => {
  let data = {
    userInfo: req.userInfo,
    id: req.query.contentid,
    categories: [],
    content: '',
    count: 0
  }
  Category.find().sort({
    _id: -1
  }).then(categories => { // 获取分类信息
    data.categories = categories
    return Content.findOne({
      _id: req.query.contentid
    }).populate(['user'])
  }).then(rs => {
    if (!rs) {
      res.render('admin/error.html', {
        userInfo: req.userInfo,
        message: '没有此文章 !',
        type: 'panel-danger'
      })
    } else {
      rs.views++
      rs.save()
      data.content = rs.content
      data.views = rs.views
      data.title = rs.title
      data.addTime = rs.addTime
      data.user = rs.user
      data.comments = rs.comments
      res.render('main/view.html', data)
    }
  })
})


module.exports = router
